<?php
namespace app\resources\event;
use help\IpHelp;
use think\facade\Cookie;
use app\admin\model\SystemLog;
use app\resources\tasks\LogTask;

/**
 * 请求日志
 * @package app\event
 */
class RequestLog
{

    /**
     * 执行句柄
     */
    public function handle($data)
    {
        $result = $data->getData();
    	if(gettype($result) == 'array' && !strstr( request()->pathinfo(),"apidoc") ){
            try {
                try {
                    $request = request();
                    $referer = $request->server('HTTP_REFERER');
                    $userInfo = $request->userInfo ?: [];

                    //判断是否需要加入
                    if( strstr(strtolower( getActiveUrl() ),"/msg/")  ){
                        return true;
                    }
                    if( strstr(strtolower( getActiveUrl() ),"install/create")   ){
                        return true;
                    }
                    if( strstr($referer,"/system/logMng/index") ){
                        return true;
                    }

                    $data=[];
                    $data['uid'] = $userInfo['user_id'] ?? ($userInfo['id'] ?? '');
                    $data['userinfo'] =  json_encode( $userInfo ,JSON_UNESCAPED_UNICODE);
                    $data['client_ip'] = IpHelp::getOnlineIp();
                    $data['api'] = strtolower( getActiveUrl() );
                    $data['referer'] = $referer;
                    $data['token'] =  $request->header('x-admin-token') ?: Cookie::get('x-admin-token') ?: $request->header('x-token');
                    $data['cookie'] = json_encode(Cookie::get(),JSON_UNESCAPED_UNICODE);
                    $data['param'] = json_encode( $request->param() ,JSON_UNESCAPED_UNICODE);
                    $data['status'] = ($result["code"] ?? '') == 0  ?  1 :  0;
                    $data['result'] = ($result["code"] ?? '') == 0 ? '{"code":0,"data":"","msg":"操作成功"}' : json_encode( $result ,JSON_UNESCAPED_UNICODE);
                    $data['create_time'] = date('Y-m-d H:i:s');

                    app('swoole.server')->task([ LogTask::class, $data ]);
                } catch (\Exception $e) {
                    SystemLog::record($result);
                }
            } catch (\Exception $e) {
                SystemLog::record($result);
            }
    	}
    }
    
}
